package com.quan.system.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quan.commons.core.MyBaseController;
import com.quan.commons.properties.SysProperties;
import com.quan.commons.utils.DateUtils;
import com.quan.commons.utils.FileUtils;
import com.quan.commons.utils.PageUtils;
import com.quan.commons.utils.RandomUitl;
import com.quan.commons.vo.R;
import com.quan.system.commons.vo.SysFileVo;
import com.quan.system.entity.SysFile;
import com.quan.system.service.SysFileService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.util.*;


/**
 * 系统-文件表
 * @author yhaoquan
 * @email yhaoquan@163.com
 * @date 2021-01-04 22:24:24
 */
@Slf4j
@Api(tags = "系统-文件表")
@RestController
@RequestMapping("/system/sysfile")
public class SysFileController extends MyBaseController {

    @Autowired
    private SysFileService service;

    @Autowired
    private SysProperties properties;


    /**
     * 保存
     *
     * @param vo
     * @return
     */
    @PostMapping("save")
    public R save(@Valid @RequestBody SysFileVo vo) {
        this.service.save(vo);
        return R.ok();
    }

    /**
     * 修改
     * @param vo
     * @return
     */
    @PostMapping("update")
    public R update(@Valid @RequestBody SysFileVo vo) {
        this.service.updateById(vo);
        return R.ok();
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @PostMapping("delete")
    public R delete(@RequestBody Long[] ids) {
        if (null != ids && ids.length > 0) {
            this.service.removeByIds(Arrays.asList(ids));
            return R.ok();
        } else {
            return R.failure();
        }
    }

    /**
     * 多条件查询信息详情
     * @param vo
     * @return
     */
    @GetMapping("/info")
    public R info(SysFileVo vo) {
        QueryWrapper<SysFile> queryWrapper = new QueryWrapper<SysFile>(vo);
        SysFile sysFile = this.service.getOne(queryWrapper);
        return R.ok().put("data", sysFile);
    }

    /**
     * 根据ID查询信息详情
     * @param {id}
     * @return
     */
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        SysFile sysFile = this.service.getById(id);
        return R.ok().put("data", sysFile);
    }

    /**
     * 列表查询
     * @param vo
     * @return
     */
    @GetMapping(value = "list")
    public Object list(SysFileVo vo) {
        List<SysFileVo> list = this.service.queryList(new PageUtils(request), vo);
        return R.ok().put("data", list);
    }

    /**
     * 分页查询
     * @param vo
     * @return
     */
    @GetMapping(value = "page")
    public R queryPage(SysFileVo vo) {
        PageUtils page = this.service.queryPage(new PageUtils(request), vo);
        return R.ok().data(page);
    }

    /**
     * 文件上传
     * 注意：文件上传要在docker-componse下映射目录
     * # 映射文件上传的目录
     * - /root/whizen_website_2023/install/nginx/html/upload:/root/whizen_website_2023/install/nginx/html/upload
     * @param request
     * @param destDir
     * @return
     */
    @PostMapping(value = "/upload")
    public Object upload(HttpServletRequest request, String destDir, String canDataPath) {
        try {
            String path = this.properties.getUpload() + File.separator;
            String folder = (StringUtils.isNotBlank(destDir) ? destDir + File.separator : "");
            // 如果canDataPath参数为空，则路径加上今天的日期作为目录
            if (StringUtils.isBlank(canDataPath)) {
                folder += DateUtils.getDate(DateUtils.YYYYMMDD) + File.separator;
            }
            FileUtils.createDir(path + folder);

            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

            // 取得MultiValueMap集合
            MultiValueMap<String, MultipartFile> multiFileMap = multipartRequest.getMultiFileMap();
            Set<Map.Entry<String, List<MultipartFile>>> entrySet = multiFileMap.entrySet();
            for (Map.Entry<String, List<MultipartFile>> entry : entrySet) {

                // 获取MultipartFile集合
                List<MultipartFile> multipartFiles = entry.getValue();
                for (MultipartFile multipartFile : multipartFiles) {
                    String extension = FilenameUtils.getExtension(multipartFile.getOriginalFilename());
                    String filename = DateUtils.format(new Date(), DateUtils.YYYYMMDDHHMMSSS) + "_" + RandomUitl.generateInteger(4) + "." + extension;
                    String dest = path + folder + filename;

                    multipartFile.transferTo(new File(dest));

                    String url = this.properties.getUploadUrl() + folder + filename;

                    SysFile entity = new SysFile();
                    entity.setName(filename);
                    entity.setSize(multipartFile.getSize());
                    entity.setType(multipartFile.getContentType());
                    entity.setPath(FilenameUtils.separatorsToUnix(folder + filename));
                    entity.setHref(FilenameUtils.separatorsToUnix(url));
                    this.service.save(entity);

                    log.info("==>上传成功");
                    log.info("==>存放地址: {}", dest);
                    log.info("==>访问地址: {}", entity.getHref());

                    return R.ok().put("data", entity);
                }
            }
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
        return R.ok();
    }

    //public Object upload(HttpServletRequest request, String destDir) {
    //    try {
    //        String path = this.properties.getUpload() + File.separator;
    //        String folder = (StringUtils.isNotBlank(destDir) ? destDir + File.separator : "") + DateUtils.getDate(DateUtils.YYYYMMDD) + File.separator;
    //        File ff = new File(path + folder);
    //        if(!ff .exists()){
    //            ff .mkdirs();
    //            log.info("file 目录创建成功！");
    //        }
    //        final File dir = FileUtils.createDir(path + folder);
    //
    //        log.info(path + folder);
    //        log.info(dir.getAbsolutePath());
    //        log.info(dir.getAbsolutePath());
    //
    //        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    //
    //        // 取得MultiValueMap集合
    //        MultiValueMap<String, MultipartFile> multiFileMap = multipartRequest.getMultiFileMap();
    //        Set<Map.Entry<String, List<MultipartFile>>> entrySet = multiFileMap.entrySet();
    //        for (Map.Entry<String, List<MultipartFile>> entry : entrySet) {
    //
    //            // 获取MultipartFile集合
    //            List<MultipartFile> multipartFiles = entry.getValue();
    //            for (MultipartFile multipartFile : multipartFiles) {
    //
    //                String extension = FilenameUtils.getExtension(multipartFile.getOriginalFilename());
    //                String filename = DateUtils.format(new Date(), DateUtils.YYYYMMDDHHMMSSS) + "_" + RandomUitl.generateInteger(4) + "." + extension;
    //                String dest = path + folder + filename;
    //
    //                log.info(dest);
    //
    //                final File fileDest = new File(dest);
    //                multipartFile.transferTo(fileDest);
    //
    //                fileDest.setExecutable(false, false);
    //                fileDest.setWritable(true, true);
    //                fileDest.setReadable(true, false);
    //
    //                String url = this.properties.getUploadUrl() + folder + filename;
    //
    //                SysFile entity = new SysFile();
    //                entity.setName(filename);
    //                entity.setSize(multipartFile.getSize());
    //                entity.setType(multipartFile.getContentType());
    //                entity.setPath(FilenameUtils.separatorsToUnix(folder + filename));
    //                entity.setHref(FilenameUtils.separatorsToUnix(url));
    //                this.service.save(entity);
    //
    //                log.info("==>上传成功");
    //                log.info("==>存放地址: {}", dest);
    //                log.info("==>访问地址: {}", entity.getHref());
    //
    //                return R.ok().put("data", entity);
    //
    //            }
    //        }
    //    } catch (Exception e) {
    //        return R.error(e.getMessage());
    //    }
    //    return R.ok();
    //}

}
